//定制请求的实例

//导入axios  npm install axios
import axios from 'axios';
import {useTokenStore} from "@/stores/token.js";
import {useRouter} from "vue-router";
//定义一个变量,记录公共的前缀
const baseURL = '/api';
const instance = axios.create({baseURL})
import router from '@/router/index.js'
// 添加请求拦截器
instance.interceptors.request.use(
    config => {
        const tokenStore = useTokenStore()
        if (tokenStore.token) {
            config.headers.Authorization = tokenStore.token
        }
        return config
    },
    error => {
        Promise.reject(error);
    }
);

//添加响应拦截器
instance.interceptors.response.use(
    result => {
        // 状态码 0 表示成功
        if (result.data.code === 0) {
            return result.data;
        }
        alert(result.data.message || '服务异常')
        return Promise.reject(result.data);
    },
    err => {
        if (err.response.status === 401) {
            router.push('/login')
            alert("请先登录");
        } else {
            alert('服务异常');
        }
        return Promise.reject(err);//异步的状态转化成失败的状态
    }
)

export default instance;